local skynet = require "skynet"
local filelog = require "filelog"
local msghelper = require "agenthelper"
local processstate = require "processstate"
local playerdatadao = require "playerdatadao"
local configdao = require "configdao"
local tabletool = require "tabletool"
local timetool = require "timetool"
local tostring = tostring
require "enum"

local processing = processstate:new({timeout=4})

local GetGiftrecords = {}

--[[
//请求玩家的邮件信息
message GetGiftrecordsReq {
	optional Version version = 1;
	optional int32 id = 2;
	optional int32 create_time = 3;
}

message GiftrecordItem {
    optional int32 id = 1;
    optional int32 from_rid = 2;
    optional string from_rolename = 3;
    optional string from_logo = 4;
    optional int32 to_rid = 5;
    optional string to_rolename = 6;
    optional string to_logo = 7;
    optional int32 gemstone = 8;
    optional create_time = 9;
}

//响应玩家的房卡赠送记录信息
message GetGiftrecordsRes {
	optional int32 errcode = 1; //错误原因 0表示成功
	optional string errcodedes = 2; // 错误描述 
	repeated GiftrecordItem giftrecords = 3; // 玩家赠送房卡记录列表
}
--]]

function  GetGiftrecords.process(session, source, fd, request)
    local responsemsg = {
        errcode = EErrCode.ERR_SUCCESS,
    }
    local server = msghelper:get_server()

    --检查当前登陆状态
	if not msghelper:is_login_success() then
		filelog.sys_error("GetGiftrecords.process invalid server state", server.state)
		responsemsg.errcode = EErrCode.ERR_INVALID_REQUEST
		responsemsg.errcodedes = "无效的请求!"
		msghelper:send_resmsgto_client(fd, "GetGiftrecordsRes", responsemsg)		
		return
	end

	if processing:is_processing() then
        responsemsg.errcode = EErrCode.ERR_DEADING_LASTREQ
        responsemsg.errcodedes = "正在处理上一次请求！"
        msghelper:send_resmsgto_client(fd, "GetGiftrecordsRes", responsemsg)
        return
    end


	local status
	local giftrecords
	local condition = ""
	local givegift_show_days = configdao.get_businessconfitem_by_index(100, 1000, "globalvarcfg", "givegift_show_days")
   	if request.create_time == 0 then
   		local difftime = timetool.get_time() - (givegift_show_days*24*3600)
		if givegift_show_days > 0 and difftime > 0 then
			condition = condition .. "select * from role_giftrecords where from_rid="..tostring(server.rid)..
			" and create_time >=" .. difftime
		else
			condition = condition .. "select * from role_giftrecords where from_rid="..tostring(server.rid)..
			" and create_time >= 0"
		end
   	else
   		condition = condition .. "select * from role_giftrecords where from_rid="..tostring(server.rid)..
			" and create_time >=" .. request.create_time
   	end
    processing:set_process_state(true)

	status, giftrecords = playerdatadao.query_player_giftrecords(server.rid, condition)

    processing:set_process_state(false)

	responsemsg.giftrecords = giftrecords

    msghelper:send_resmsgto_client(fd, "GetGiftrecordsRes", responsemsg)
end


return GetGiftrecords
